package cn.lirenyi.org.service.impl;

import cn.lirenyi.basic.service.impl.BaseServiceImpl;
import cn.lirenyi.basic.util.MD5Utils;
import cn.lirenyi.basic.util.PageList;
import cn.lirenyi.basic.util.StrUtils;
import cn.lirenyi.org.domain.Employee;
import cn.lirenyi.org.mapper.EmployeeMapper;
import cn.lirenyi.org.query.EmployeeQuery;
import cn.lirenyi.org.service.IEmployeeService;
import cn.lirenyi.user.domain.Logininfo;
import cn.lirenyi.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper emloyeeMapper;

    @Autowired
    private LogininfoMapper loginInfoMapper;
  /*
     级联操作引用属性
   */
    @Override
    public void add(Employee employee) {
        //1.设置用户的盐值和密码加密
        initEmployee(employee);
        //复制一个LoginInfo
        Logininfo info =  employee2LoginInfo(employee);
        loginInfoMapper.add(info);
        employee.setLogininfo_id(info.getId());
        emloyeeMapper.add(employee);
        super.add(employee);
    }

    private Logininfo employee2LoginInfo(Employee employee) {
        Logininfo info = new Logininfo();
        BeanUtils.copyProperties(employee,info);
        // 后台员工type应该设置成0
        info.setType(0);
        return info;
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
    }

    @Override
    public void update(Employee employee) {
        Logininfo logininfo = loginInfoMapper.queryById(employee.getLogininfo_id());
        if(logininfo != null){
            BeanUtils.copyProperties(employee, logininfo);
            loginInfoMapper.update(logininfo);
            emloyeeMapper.update(employee);
        }
    }

    @Override
    public void del(Long id) {
        Employee employee = emloyeeMapper.queryById(id);
        loginInfoMapper.del(employee.getLogininfo_id());
        emloyeeMapper.del(id);
    }
}

